package org.web2024.service.serviceimp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.web2024.dao.Course;
import org.web2024.mapper.UserMapper;
import java.time.LocalDateTime;
import java.util.Set;



@Component
public class CourseService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserMapper userMapper;
    @Scheduled(cron = "0 0 * * * ?")//每小时执行
    public void changeCourseTime(){
        String endTime = (String) redisTemplate.opsForHash().get("currentterm","endtime");
        if(endTime!=null){
            LocalDateTime end=LocalDateTime.parse(endTime);
            if(LocalDateTime.now().isAfter(end)){
              CourseSer();
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void CourseSer(){
        //String term=(String) redisTemplate.opsForHash().get("currentterm","term");
        Set<String> keys = redisTemplate.keys("course:*" );
        if(keys==null)
            return;
        keys.forEach(key->{
            Course course=(Course) redisTemplate.opsForValue().get("course:"+key);
            Set<ZSetOperations.TypedTuple<Object>> students=redisTemplate.opsForZSet().reverseRangeWithScores(key,0,course.getC_count());
            if(students!=null&&!students.isEmpty()){
                students.forEach(student->{
                    String s_no=(String) student.getValue();
                    userMapper.insertsc(s_no,key);
                });
            }
        });
        redisTemplate.delete("currentterm");
        redisTemplate.delete("course");
        redisTemplate.delete("coursecoin");
        redisTemplate.delete("student");
    }
}
